﻿using Amazon.S3;
using Autofac;
using System.Reflection;
using WMS.Repository.IRepository;
using WMS.Repository;
using WMS.Service.IService;
using WMS.Service.Minio;
using WMS.Service;
using WMS.Common.Minio;
using WMS.Common;
using WMS.Extensions;

public class AutofacModuleRegister : Autofac.Module
{
    protected override void Load(ContainerBuilder builder)
    {
        var basePath = AppContext.BaseDirectory;
        var servicesDllFile = Path.Combine(basePath, "WMS.Service.dll");
        var repositoryDllFile = Path.Combine(basePath, "WMS.Repository.dll");

        // 1. 注册泛型仓储基类
        builder.RegisterGeneric(typeof(BaseRepository<>))
               .As(typeof(IBaseRepository<>))
               .InstancePerDependency();

        // 2. 注册泛型服务基类
        builder.RegisterGeneric(typeof(BaseServices<>))
               .As(typeof(IBaseService<>))
               .InstancePerDependency();

        // 3. 注册服务层程序集中的所有服务
        var assemblysServices = Assembly.LoadFrom(servicesDllFile);
        builder.RegisterAssemblyTypes(assemblysServices)
               .AsImplementedInterfaces()
               .InstancePerDependency();

        // 4. 注册仓储层程序集中的所有仓储
        var assemblysRepository = Assembly.LoadFrom(repositoryDllFile);
        builder.RegisterAssemblyTypes(assemblysRepository)
               .AsImplementedInterfaces()
               .InstancePerDependency();

        // 5. 注册 MinIO 相关服务
        RegisterMinioServices(builder);
    }

    private void RegisterMinioServices(ContainerBuilder builder)
    {
        // 注册 IAmazonS3 客户端
        builder.Register(context =>
        {
            // 使用 AppSettings 获取配置
            var minioSettings = AppSettings.GetOptions<MinioSettings>();

            // 确保 Endpoint 包含协议
            var endpoint = minioSettings.Endpoint;
            if (!endpoint.StartsWith("http://") && !endpoint.StartsWith("https://"))
            {
                endpoint = minioSettings.WithSSL ? $"https://{endpoint}" : $"http://{endpoint}";
            }

            var config = new AmazonS3Config
            {
                ServiceURL = endpoint,  // 使用完整的 URL
                ForcePathStyle = true, 
                UseHttp = !minioSettings.WithSSL,
                AuthenticationRegion = minioSettings.Region
            };

            return new AmazonS3Client(
                minioSettings.AccessKey,
                minioSettings.SecretKey,
                config
            );
        }).As<IAmazonS3>()
          .SingleInstance();

        // 注册 MinioService
        builder.RegisterType<MinioService>()
               .As<IMinioService>()
               .InstancePerLifetimeScope();

        // 注册 MinioSettings 配置
        builder.Register(_ => AppSettings.GetOptions<MinioSettings>())
               .AsSelf()
               .SingleInstance();

        builder.RegisterType<MinioSetupService>().AsSelf().SingleInstance();
    }
}